<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>支付配置</cite></a>
    <a><cite>转卡通道配置</cite></a>
    <a><cite>短信通知</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">商户通知列表</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form" style="float:right; margin-bottom: 10px;">
              <div id="timeDiv" class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="orderId" id="searchOrderId" placeholder="订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <select name="orderType" id="searchOrderType" lay-search="">
                    <option value="">类型</option>
                    <option value="1">支付</option>
                    <option value="2">转账</option>
                    <option value="3">退款</option>
                    <option value="4">代付</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <select name="status" id="searchStatus" lay-search="">
                    <option value="-99">通知状态</option>
                    <option value="1">通知中</option>
                    <option value="2">通知成功</option>
                    <option value="3">通知失败</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                    <a id="search" class="layui-btn" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
                </div>
              </div>
            </div>
          </div>
          <div class="layui-row">
            <div class="layuiAdmin-btns" style="margin-bottom:10px;">
              <a class="layui-btn" id="batchResendBtn"><i class="layui-icon layui-icon-release"></i>重发通知</a>
              <a class="layui-btn layui-btn-danger relationDelete"><i class="layui-icon layui-icon-delete"></i>彻底删除</a>
            </div>
          </div>
          <table id="XxPay_Mgr_Notify_dataAll" lay-filter="XxPay_Mgr_Notify_dataAll"></table>
        </div>

      </div>
    </div>
  </div>
</div>

<script>
layui.use(['admin', 'table', 'util', 'timePick'], function(){
  var $ = layui.$
  ,admin = layui.admin
  ,table = layui.table
  ,element = layui.element
  ,view = layui.view
  ,form = layui.form
  ,timePick = layui.timePick;

  timePick.init();  //第一个参数表示开始时间   第二个表示结束时间   0,0今天   -1,-1昨天   -7,0近一周   以此类推
  element.render('breadcrumb', 'breadcrumb');

    $("#batchResendBtn").off().on("click", function(){
    	$('#reNotify').attr('disabled',true);
        var load = layer.msg('重新发送中...', {
	        icon: 16
	        ,shade: 0.01
	        ,time: 9999999999
        });

        var orderIds = [];
        var errorMsg = "";
        $.each(table.cache.tableReload, function(){


            var thisObject = $(".layui-table tr[data-index='"+this.LAY_TABLE_INDEX+"'] input[name='layTableCheckbox']");
            if(thisObject.is(':checked')){ //勾选状态
                /*if(this.status == '2'){
                    errorMsg = "无法发送通知状态为成功的通知消息！";
                    return false;
                }*/
                orderIds.push(this.orderId);
            }
        });
        if(errorMsg) return layer.alert(errorMsg);
        if(orderIds.length <= 0) return layer.alert("请勾选需要重发的订单！");
        if(orderIds.length > 10) return layer.alert("批量重发商户通知个数不得大于10个！");

        admin.req({
            type: 'post',
            url: layui.setter.baseUrl + '/mch_notify/resend',
            timeout: 1000 * 60,
            data: {orderIds : JSON.stringify(orderIds)},
            error: function(err){
            	layer.close(load);
            	layer.alert(err);
            },
            success: function(res){
								layer.close(load);
                if(res.code == 0 ) {
                    if(res.data.errMsg){
                        layer.alert(res.data.errMsg);
                    }else{
                        layer.alert("重发成功！, 共发送"+ res.data.sendCount + "条通知！",function(layid){
                            layer.close(layid);
                            table.reload('tableReload');
                        });
                    }
                    $('#reNotify').attr('disabled',false);
                    return false;
                }
            }
        });

    });

  var tplStatus = function(d){
    if(d.status == 1) {
      return "<span style='color: blue'>通知中</span>";
    }else if(d.status == 2) {
      return "<span style='color: green'>通知成功</span>";
    }else if(d.status == 3) {
      return "<span style='color: red'>通知失败</span>";
    }
  };

  var tplType = function(d){
    if(d.orderType == 1) {
      return "支付";
    }else if(d.orderType == 2) {
      return "转账";
    }else if(d.orderType == 3) {
      return "退款";
    }else if(d.orderType == 4) {
      return "代付";
    }
  };

  //标题内容模板
  var tplTitle = function(d){
      return "<a class='layui-btn layui-btn-xs layui-btn-primary' lay-event='detail'><i class='layui-icon layui-icon-about'></i>查看</a>";
  };

  //通知列表，默认查今天
  var createTimeStart = $('#createTimeStart').val();
  var createTimeEnd = $('#createTimeEnd').val();
  table.render({
    elem: '#XxPay_Mgr_Notify_dataAll'
    ,url: layui.setter.baseUrl + '/mch_notify/list' //通知列表接口
    ,where: {
        access_token: layui.data(layui.setter.tableName).access_token,
        createTimeStart: createTimeStart,
        createTimeEnd: createTimeEnd
    }
    ,id: 'tableReload'
    ,page: true
    ,cols: [[
          {type: "checkbox", fixed: 'left'}
      ,{field: 'orderId', width: 220, title: '订单号'}
      ,{field: 'mchId', title: '商户ID'}
      /*,{field: 'appId', title: '应用ID'}*/
      ,{field: 'orderType', title: '订单类型', templet: tplType}
      ,{field: 'notifyCount', title: '通知次数'}
      ,{field: 'status', title: '状态', templet: tplStatus}
      ,{field: 'lastNotifyTime', title: '最后通知', width: 200, templet: '<div>{{ d.lastNotifyTime == null ? "" : layui.util.toDateString(d.lastNotifyTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
      ,{field: 'createTime', title: '创建时间', width: 200, templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
      ,{field: 'edit', title: '操作', width: 100, fixed: 'right', templet: tplTitle }
    ]]
      ,skin: 'line'
  });

  //监听工具条
  table.on('tool(XxPay_Mgr_Notify_dataAll)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){
      view.xxpayPopup("查看通知", "order/notify/view", {orderId: data.orderId}, {btn:false, area:["60%", "60%"]});
    }
  });


    $('.layuiAdmin-btns .relationDelete').on('click', function() {
        var checkedData = table.checkStatus("tableReload").data; //获得选中的数据
        if (checkedData.length === 0) return layer.msg('请选择数据');
        var delIds = [];
        $.each(checkedData, function () {
            delIds.push(this.orderId);
        });

        //弹层
        var relationDeleteHtml = `
                <div style="color:red; margin:20px; padding-left:50px" >
                    <label class="layui-inline"> 此操作将删除选中数据及所有关联数据！是否继续删除？</label><br/><br/>
                    <label class="layui-inline"> 关联表：[商户通知表];</label>
                </div>
                <form class="layui-form center">
                     <div class="layui-form-item" style="margin-top:20px">
                        <label class="layui-form-label" style="width:130px;">平台超级密码：</label>
                        <div class="layui-input-inline" style="width: 312px;">
                            <input type="password" autocomplete="off" class="layui-input relationDeletePassword">
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top:30px">
                        <div class="layui-input-block" style="margin-left: 180px;">
                            <button type="button" class="layui-btn layui-btn-danger relationDeleteBtn">确认删除</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="layer.closeAll();">取消</button>
                        </div>
                    </div>
                </form>
            `;
        //打开弹层
        var thisLayerId = layer.open({type: 1, area: ['520px', 'auto'], title: '提示', content: relationDeleteHtml});
        $(".relationDeleteBtn").click(function () {
            var relationDeletePassword = $('.relationDeletePassword').val();
            if(!relationDeletePassword) return layer.msg('请输入平台超级密码！');

            var layerMsgId = layer.msg('正在执行删除任务... ', {time: 0, shade: 0.3});
            admin.req({
                type: 'get',
                url: layui.setter.baseUrl + '/mch_notify/relationDelete',
                data: {ids: JSON.stringify(delIds), superPassword: relationDeletePassword},
                error: function (err) {
                    layer.close(layerMsgId);
                    layer.alert(err);
                },
                success: function (res) {
                    layer.close(layerMsgId);
                    if (res.code == '0') { //成功创建任务
                        layer.close(thisLayerId);
                        table.reload('tableReload');  //刷新页面
                        layer.alert("操作成功, 共删除了 "+res.data+" 条关联数据！");
                    }
                },
                complete:function () {
                    layer.close(layerMsgId);
                }
            });
        });
    });

  // 搜索
  var $ = layui.$, active = {
    reload: function(){
      var orderId = $('#searchOrderId').val();
      var orderType = $("#searchOrderType").val();
      var status = $("#searchStatus").val();
      var createTimeStart = $('#createTimeStart').val();
      var createTimeEnd = $('#createTimeEnd').val();
      //执行重载
      table.reload('tableReload', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          orderId: orderId,
          orderType: orderType,
          status : status,
          createTimeStart : createTimeStart,
          createTimeEnd : createTimeEnd
        }
      });
    }
  };
  $('#search').on('click', function() {
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });
  // 渲染表单
  form.render();
});
</script>